package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

var db *sqlx.DB

func initDB() (err error) {
	dsn := "root:HYJ=wvs1996@tcp(127.0.0.1:3306)/db1?charset=utf8mb4&parseTime=True" //parseTime=True讲go中的time对象转化为数据库的时间对象
	db, err = sqlx.Connect("mysql", dsn)                                             //MustConnect()如果出现错误，自动panic，而Connect需要自己处理err
	if err != nil {
		fmt.Printf("连接出错，%v\n", err)
		panic(err)
	}
	db.SetMaxOpenConns(50)
	db.SetConnMaxIdleTime(10)
	return
}

type User struct {
	Id   int    `db:"id"`
	Name string `db:"name"`
	Age  int    `db:"age"`
}

//1、查询
func query(param interface{}) {
	var u User
	sqlStr := "select * from users_info where id=?"
	if err := db.Get(&u, sqlStr, param); err != nil {
		fmt.Printf("查询出错，%v\n", err)
		return
	}
	fmt.Printf("查询结果：%#v", u)

}

//1、多条数据查询(传入的是slice，返回的也是slice)
func queryRows(param1, param2 interface{}) {
	var u []User
	sqlStr := "select * from users_info where id in (?,?)"
	if err := db.Select(&u, sqlStr, param1, param2); err != nil {
		fmt.Printf("查询出错，%v\n", err)
		return
	}
	fmt.Printf("查询结果：%#v", u) //[]main.User{main.User{Id:2, Name:"jack", Age:20}, main.User{Id:3, Name:"tom", Age:22}}

}

//2、sqlx中的删、改、查，还是使用exec方法与原生sql中的exec使用一样

func main() {
	initDB()
	queryRows(2, 3)

}
